﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace AIC_PN
{
    public class PrepareDataForTreeViewMau6
    {
        public void PopulateRootLevel(TreeView trvDonVi, int TenBaoCaoID_DM)
        {
            string sql = "SELECT ID,MaDM,TenDM,(select count(*) FROM dbo.tblDanhMucBaoCaoMau6 WHERE FatherID=DV.ID) childnodecount  " +
                         "FROM dbo.tblDanhMucBaoCaoMau6 DV Where DV.FatherID = DV.ID AND MaDM = " + TenBaoCaoID_DM;
                         //"FROM dbo.tblDanhMucBaoCaoMau6 DV Where FatherID=DV.ID AND MaDM = " + TenBaoCaoID_DM;
            DataTable tblRootNode = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            PopulateNodes(tblRootNode, trvDonVi.Nodes);
        }

        public void PopulateSubLevel(int FatherID, TreeNode parentNode)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@FatherID", SqlDbType.Int, ParameterDirection.Input, FatherID));
            string sql = "SELECT ID,MaDM,TenDM,( SELECT COUNT(*) FROM dbo.tblDanhMucBaoCaoMau6 WHERE FatherID = DV.ID) childnodecount " +
                         "FROM dbo.tblDanhMucBaoCaoMau6 DV WHERE DV.FatherID = @FatherID AND DV.FatherID != DV.ID";
            DataTable tblSubNode = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            PopulateNodes(tblSubNode, parentNode.ChildNodes);
        }

        public void PopulateNodes(DataTable tblNode, TreeNodeCollection arrNodes)
        {
            foreach (DataRow dr in tblNode.Rows)
            {
                TreeNode tn = new TreeNode();
                tn.Text = dr["TenDM"].ToString();
                tn.Value = dr["ID"].ToString();
                arrNodes.Add(tn);
                tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
            }
        }
    }
}
